<?php
/**
 * @todo add table subscriber to constructor
 */
class Itc_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
	
	protected $search_fields = array();
	
	public function getPaginator($adapter_data,$page = 1,$page_items = 10,$page_range = 10){
		if(is_array($adapter_data)){
			$adapter = new Zend_Paginator_Adapter_Array($adapter_data);
		}elseif($adapter_data instanceof Zend_Db_Select){
			$adapter = new Zend_Paginator_Adapter_DbSelect($adapter_data);
		}elseif($adapter_data instanceof Zend_Db_Table_Select){
			$adapter = new Zend_Paginator_Adapter_DbTableSelect($adapter_data);
		}else{
			require_once "Zend/Db/Table/Exception.php";
			throw new Zend_Db_Table_Exception("Unsupported paginator adapter data.Expected: Zend_Db_Select, Zend_Db_Table_Select, Array.");
		}
		$paginator = new Zend_Paginator($adapter);
		$paginator->setCurrentPageNumber($page);
		$paginator->setItemCountPerPage($page_items);
		$paginator->setPageRange($page_range);
		
		return $paginator;
	}
	
	public function setSearchFields($search_fields){
		if(!is_array($search_fields)){
			$search_fields = array($search_fields);
		}
		
		$this->search_fields = $search_fields;
		
		return $this;
	}
	
	function getGridData($params,Zend_View_Interface $view = null, $cols = Zend_Db_Select::SQL_WILDCARD){
		$select = $this->select()
						->from(
						 	array('t' => $this->info(Zend_Db_Table::NAME)),
							$cols
						);
		
		if(!empty($params['query'])){
			$where = array();
			foreach($this->search_fields as $key => $name){
				$where[] = "`{$name}` LIKE '%".mysql_escape_string($params['query'])."%'";
			}
			if(!empty($where)){
				$select->where("(".implode(" OR ", $where).")");
			}
		}
		
		$page = 1;
		$page_items = 10;
		$page_range = 10;
		
		if(isset($params['limit']) && $params['limit'] > 0){
			$page_items = $params['limit'];
		}
		
		if(isset($params['pc_range']) && $params['pc_range'] > 0){
			$page_range = $params['pc_range'];
		}
		
		if(isset($params['start']) && $params['start'] > 0){
			$page = $params['start'] / $page_items + 1;
		}
		
		$paginator = $this->getPaginator($select,$page,$page_items,$page_range);
		
		$data = array(
			'data'	=> (array)$paginator->getCurrentItems(),
			'total'	=> $paginator->getTotalItemCount()
		);
		
		if($view !== null){
			$view->data = $data['data'];
			$view->total = $data['total'];
		}
		
		return $data;
	}

    public function save(array $data)
    {
        $data = $this->clearData($data);
        if (empty($data[$this->_primary])) {
            unset($data[$this->_primary]);
            $res = $this->insert($data);
        } else {
            $res = $this->update($data, array($this->_primary . ' = ?' => $data[$this->_primary]));
        }

        return $res;
    }

    public function clearData($data)
    {
        if (!is_array($data)) {
            $data = array($data);
        }
		$cols = $this->_getCols();

        foreach ($data as $key => $value) {
            if (!in_array($key, $cols)) {
                unset($data[$key]);
            }
        }

        return $data;
    }

	/**
	 * Delete single Row by Id
	 * @return void
	 */
	public function deleteById($id)
	{
		$id = (int)$id;
		if ($id > 0){
			$this->delete(array($this->_primary . ' = ?' => $id));
		}
	}
}